<?php
/* PV log : output as an image */
header('Content-Type: image/bmp');
echo base64_decode("Qk06AAAAAAAAADYAAAAoAAAAAQAAAP////8BABgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////AA==");
header("Content-Encoding: none");
header("Content-Length: ".ob_get_length());
header('Connection: Close');
$page_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$time_stamp = $_SERVER['REQUEST_TIME'].'';
$user_agent = '';
$ip = '';
if (!isset($_COOKIE['user_id'])) {
    $user_id = md5(uniqid('',1));
    setcookie('user_id', $user_id, time()+864000000, '/'); // lifetime > 27 years
} else {
    $user_id = $_COOKIE['user_id'];
}
if (!isset($_COOKIE['session_id'])) {
    $session_id = md5(uniqid('',1));
    setcookie('session_id', $session_id, 0, '/'); // session lifetime
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $ip = real_ip();//only log ua & ip in the 1st session
} else {
    $session_id = $_COOKIE['session_id'];
}
$pv_id = md5(uniqid('',1));
setcookie('pv_id', $pv_id, 0, '/'); // change once page loaded

$pv_log = compact('page_url', 'user_agent', 'ip', 'time_stamp', 'user_id', 'session_id', 'pv_id');
apache_note('tracking_log', json_encode($pv_log));

//function
function real_ip()
{
    $realip = NULL;
    if ($realip !== NULL)
    {
        return $realip;
    }
    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);
                if ($ip != 'unknown')
                {
                    $realip = $ip;
                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $realip;
}
